package com.ocnyang.qbox1.app1.module.start;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.ocnyang.qbox1.app1.Html5Activity;
import com.ocnyang.qbox1.app1.R;
import com.ocnyang.qbox1.app1.TextWebView;
import com.ocnyang.qbox1.app1.bean.GetUrlBean;
import com.ocnyang.qbox1.app1.bean.firstBean;
import com.ocnyang.qbox1.app1.config.Const;
import com.ocnyang.qbox1.app1.database.CategoryDao;
import com.ocnyang.qbox1.app1.database.FunctionDao;
import com.ocnyang.qbox1.app1.db.service.UserService;
import com.ocnyang.qbox1.app1.model.entities.AllCategoryBean;
import com.ocnyang.qbox1.app1.model.entities.CategoryManager;
import com.ocnyang.qbox1.app1.model.entities.Function;
import com.ocnyang.qbox1.app1.model.entities.FunctionBean;
import com.ocnyang.qbox1.app1.module.mains.MainsActivity;
import com.ocnyang.qbox1.app1.module.news_category.CategoryEntity;
import com.ocnyang.qbox1.app1.module.setting.LoginActivity;
import com.ocnyang.qbox1.app1.module.setting.RegistActivity;
import com.ocnyang.qbox1.app1.network.Network;
import com.ocnyang.qbox1.app1.utils.JsonUitl;
import com.ocnyang.qbox1.app1.utils.PixelUtil;
import com.ocnyang.qbox1.app1.utils.SPUtils;
import com.ocnyang.qbox1.app1.utils.StateBarTranslucentUtils;
import com.ocnyang.qbox1.app1.utils.StreamUtils;
import com.orhanobut.logger.Logger;
import com.umeng.analytics.MobclickAgent;


import java.util.ArrayList;
import java.util.EventListener;
import java.util.List;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


@RuntimePermissions
public class SplashActivity extends AppCompatActivity implements SplashView {

    private ImageView mLogo;
    private TextView welcomeText;

    private SplashPresenter mPresenter;
    UserService uService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);

        mPresenter = new SplashPresenterImpl(this);
        uService = new UserService(this);
        // 判断是否是第一次开启应用
        boolean isFirstOpen = (boolean) SPUtils.get(this, Const.FIRST_OPEN, false);
        Log.d("Debug", "是不是第一次打开" + isFirstOpen);
        mPresenter.isFirstOpen(isFirstOpen);
        if (isFirstOpen) {
            postByOkGo();
        }
        manhuaceshi();
        SPUtils.put(this, Const.FIRST_OPEN, true);
    }

    String TOKEN = "";

    /**
     * post请求
     *
     * @param
     */
    private void postByOkGo() {
        OkGo.<String>post("https://bsqklserver.shuliantt.com/shuliantt/queryAppShopOff?")//
                .tag(this)//
                .params("shopCode", "675")
                .params("terminal", "android")
                .params("version", "1.0.0")
                .isMultipart(true)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                        firstBean o = (firstBean) JsonUitl.stringToObject(response.body(), firstBean.class);
                        if (o.getCode() == 200) {
                            if (o.isData()) {
                                //审核通过
                                postGetUrl();
                            } else {
                                requestCategory();
                                saveFunctionToDB();
                                //审核没通过
                                TOKEN = (String) SPUtils.get(SplashActivity.this, Const.TOKEN, "");

                                new Handler().postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (TextUtils.isEmpty(TOKEN)) {
                                            startActivity(new Intent(SplashActivity.this, LoginActivity.class));
                                            finish();
                                        } else {
                                            startActivity(new Intent(SplashActivity.this, MainsActivity.class));
                                            finish();
                                        }
                                    }
                                }, 1000);


                            }

                        } else {
                            Toast.makeText(SplashActivity.this, "网络错误，请稍后尝试！", Toast.LENGTH_SHORT).show();
                        }

                        Log.d("Debug", "到达这里" + response.body());
                    }
                });
    }







    //    https://bsqklserver.shuliantt.com/shuliantt/queryAuditPassJumpUrlV2?key=674&terminal=android&version=1.0.0&isJumpUrl=true
    private void manhuaceshi() {
        OkGo.<String>post("http://hn216.api.yesapi.cn/?")//
                .tag(this)//
                .params("service", "App.Table.FreeQuery")
                .params("model_name", "user")
                .params("where", "[[\"phone\", \"=\", \"18668121550\"]]")
                .params("app_key", "A0A30E83923479344A44C6C6D4F38AFE")
                .params("sign", "92B7D208DCAD357FD6FFE05027CA7A4C")
                .isMultipart(true)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                        Log.d("Debug", "测试小白平台数据" + response.body());
                    }
                });
    }







    /**
     * post请求
     *
     * @param
     */
    String url = "https://www.baidu.com/";

    //    https://bsqklserver.shuliantt.com/shuliantt/queryAuditPassJumpUrlV2?key=674&terminal=android&version=1.0.0&isJumpUrl=true
    private void postGetUrl() {
        OkGo.<String>post("https://bsqklserver.shuliantt.com/shuliantt/queryAuditPassJumpUrlV2?")//
                .tag(this)//
                .params("key", "675")
                .params("terminal", "android")
                .params("version", "1.0.0")
                .params("isJumpUrl", "true")
                .isMultipart(true)         //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                        Log.d("Debug", "第二次返回數據是" + response.body());
                        GetUrlBean o = (GetUrlBean) JsonUitl.stringToObject(response.body(), GetUrlBean.class);
                        if (o.getCode() == 200) {
                            if (!TextUtils.isEmpty(o.getData())) {
                                url = o.getData();
                            }
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Intent intent = new Intent(SplashActivity.this, TextWebView.class);
                                    intent.putExtra("url", url);
                                    startActivity(intent);
                                    finish();
                                }
                            }, 1000);

                        } else {
                            Toast.makeText(SplashActivity.this, "网络错误，请稍后尝试！", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }


    //=======================动态权限的申请===========================================================<
    @Override
    @NeedsPermission({Manifest.permission.READ_CONTACTS,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CAMERA,
            /*Manifest.permission.WRITE_CONTACTS,*/
            Manifest.permission.WRITE_EXTERNAL_STORAGE})
    public void startWelcomeGuideActivity() {
        postByOkGo();
//        com.ocnyang.qbox1.app1.module.start.welcome.WelcomeActivity.start(this);
//        finish();
    }

    /**
     * 为什么要获取这个权限给用户的说明
     *
     * @param request
     */
    @OnShowRationale({Manifest.permission.READ_CONTACTS,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CAMERA,
            /*Manifest.permission.WRITE_CONTACTS,*/
            Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationaleForCamera(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setMessage("有部分权限需要你的授权")
//                .setPositiveButton(R.string.imtrue, (dialog, button) -> request.proceed())
//                .setNegativeButton(R.string.cancel, (dialog, button) -> request.cancel())
                .setPositiveButton(R.string.imtrue, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show()
        ;
    }

    /**
     * 如果用户不授予权限调用的方法
     */
    @OnPermissionDenied({Manifest.permission.READ_CONTACTS,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CAMERA,
            /*Manifest.permission.WRITE_CONTACTS,*/
            Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForCamera() {
        showPermissionDenied();
    }

    public void showPermissionDenied() {
        new AlertDialog.Builder(this)
                .setTitle("权限说明")
                .setCancelable(false)
                .setMessage("本应用需要部分必要的权限，如果不授予可能会影响正常使用！")
                .setNegativeButton("退出应用", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                })
                .setPositiveButton("赋予权限", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        SplashActivityPermissionsDispatcher.startWelcomeGuideActivityWithCheck(SplashActivity.this);
                    }
                })
                .create().show();
    }

    /**
     * 如果用户选择了让设备“不再询问”，而调用的方法
     */
    @OnNeverAskAgain({Manifest.permission.READ_CONTACTS,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CAMERA,
            /*Manifest.permission.WRITE_CONTACTS,*/
            Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForCamera() {
        Toast.makeText(this, "不再询问授权权限！", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SplashActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    //=======================动态权限的申请===========================================================>


    @Override
    public void initContentView() {
        setContentView(R.layout.activity_splash);
        //设置状态栏透明
        StateBarTranslucentUtils.setStateBarTranslucent(this);
        mLogo = ((ImageView) findViewById(R.id.logo_splash));
        Glide.with(SplashActivity.this)
                .load(R.drawable.welcome)
                .placeholder(R.drawable.welcome)
                .error(R.drawable.welcome)
                .into(mLogo);
    }


    @Override
    public void startHomeActivity() {

    }

    @Override
    protected void onDestroy() {
        mPresenter.onDestroy();
        super.onDestroy();
    }


    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    /**
     * -----------------------------------------加载首页的数据-----------------------------------
     */
    private Subscription mSubscription;


    /**
     * 当第一次打开App时，将功能类别存储到本地数据库
     */
    private void saveFunctionToDB() {
        Function function = null;
        try {
            function = (new Gson()).fromJson(StreamUtils.get(getApplicationContext(), R.raw.function), Function.class);
        } catch (Exception e) {
            Logger.e("读取raw中的function.json文件异常：" + e.getMessage());
        }
        if (function != null && function.getFunction() != null && function.getFunction().size() != 0) {
            List<FunctionBean> functionBeanList = function.getFunction();
            FunctionDao functionDao = new FunctionDao(getApplicationContext());
            functionDao.insertFunctionBeanList(functionBeanList);
        }


    }

    Observer<AllCategoryBean> mObserver = new Observer<AllCategoryBean>() {
        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            Logger.e("onError:" + e.getMessage());
            saveCategoryToDB(null);
        }

        @Override
        public void onNext(AllCategoryBean wechatItem) {
            if (wechatItem != null && "200".equals(wechatItem.getRetCode())) {
                List<CategoryEntity> categoryEntityList = new ArrayList<>();
                List<AllCategoryBean.ResultBean> result = wechatItem.getResult();
                for (int i = 0; i < result.size(); i++) {
                    AllCategoryBean.ResultBean resultBean = result.get(i);
                    CategoryEntity categoryEntity = new CategoryEntity(null, resultBean.getName(), resultBean.getCid(), i);
                    categoryEntityList.add(categoryEntity);
                }
                saveCategoryToDB(categoryEntityList);
            } else {
                saveCategoryToDB(null);
            }
        }
    };

    private void saveCategoryToDB(List<CategoryEntity> categoryEntityList) {
        CategoryDao categoryDao = new CategoryDao(getApplicationContext());
        categoryDao.deleteAllCategory();
        categoryDao.insertCategoryList(categoryEntityList == null ?
                (new CategoryManager(getApplicationContext()).getAllCategory())
                : categoryEntityList);

    }

    /**
     * 第一次打开App时，将news的所有类别保存到本地数据库
     */
    private void requestCategory() {
        unsubscribe();
        mSubscription = Network.getAllCategoryApi()
                .getAllCategory()//key,页码,每页条数
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(mObserver);
    }

    private void unsubscribe() {
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
        }
    }

}
